import { View } from '@tarojs/components';
import Taro, { useRouter, useShareAppMessage, useDidShow } from '@tarojs/taro';
import { Button, Divider } from '@nutui/nutui-react-taro';
import { useEffect, useMemo, useState } from 'react';
import qs from 'qs';
import { BasicLayout } from '@/layouts';
import { useRequest } from '@/hooks';
import { getApiChoiceOutDetailId } from '@/api';
import { Media, Section } from '@/components';
// import { RouterUtil } from '@/utils';
import { StorageKey } from '@/constants/storage';
import { usePreselectStore } from '@/models';
import { Toast, parseJson } from '@/utils';
import styles from './index.module.scss';
import ProductInfo from './ProductInfo';

function Detail() {
  const router = useRouter();
  const { addDress, dresses } = usePreselectStore();
  
  // 从路由参数获取 ID 和 type（优先使用路由参数，因为这是正常跳转场景）
  const getParamsFromRouter = () => {
    const idValue = router.params?.id ? Number(router.params.id) : undefined;
    const typeValue = router.params?.type ? Number(router.params.type) : undefined;
    return { id: idValue, type: typeValue };
  };

  // 从进入选项获取参数（处理分享场景）
  const getParamsFromEnterOptions = () => {
    try {
      const enterOptions = Taro.getEnterOptionsSync();
      const query = enterOptions?.query || {};
      const idValue = query.id ? Number(query.id) : undefined;
      const typeValue = query.type ? Number(query.type) : undefined;
      return { id: idValue, type: typeValue };
    } catch {
      return { id: undefined, type: undefined };
    }
  };

  // 获取初始参数：优先从路由参数获取（正常跳转），如果没有则从进入选项获取（分享场景）
  const getInitialParams = () => {
    const routerParams = getParamsFromRouter();
    // 如果路由参数中有 id，说明是正常跳转，直接使用路由参数
    if (routerParams.id) {
      return routerParams;
    }
    // 否则可能是分享场景，从进入选项获取
    return getParamsFromEnterOptions();
  };

  // 使用 state 存储参数
  const [id, setId] = useState<number | undefined>(() => {
    return getInitialParams().id;
  });
  const [dressType, setDressType] = useState<number | undefined>(() => {
    return getInitialParams().type;
  });

  // 判断是否已预选
  const isPreselected = useMemo(() => {
    if (!id) return false;
    return dresses.some((dress) => dress.id === id);
  }, [id, dresses]);

  // 获取详情数据
  const { data: detailData = { dressInfo: {}}, loading, run: fetchDetail } = useRequest(
    getApiChoiceOutDetailId,
    {
      manual: true,
      formatResult: (res: any) => {
        const { bizData = {}, flowData, ...rest } = res?.data ?? {};
        const parsedFlowData = parseJson(flowData);
        const flowDataArray = Array.isArray(parsedFlowData)
          ? parsedFlowData
          : parsedFlowData && typeof parsedFlowData === 'object'
            ? [parsedFlowData]
            : [];

        return {
          dressInfo: { ...(parseJson(bizData ?? {}) || {}), ...rest },
          flowData: flowDataArray,
        };
      },
    },
  );

  // 初始化时获取参数
  useEffect(() => {
    const params = getInitialParams();
    if (params.id && params.id !== id) {
      setId(params.id);
    }
    if (params.type !== undefined && params.type !== dressType) {
      setDressType(params.type);
    }
  }, []);

  // 页面显示时重新获取参数（仅处理分享场景，正常跳转时路由参数应该保持不变）
  useDidShow(() => {
    // 先检查路由参数，如果有 id 说明是正常跳转，使用路由参数
      const routerParams = getParamsFromRouter();
      if (routerParams.id) {
      // 正常跳转场景，使用路由参数
      if (routerParams.id !== id) {
        setId(routerParams.id);
      }
      if (routerParams.type !== undefined && routerParams.type !== dressType) {
        setDressType(routerParams.type);
      }
    } else {
      // 可能是分享场景，从进入选项获取
      const enterParams = getParamsFromEnterOptions();
      if (enterParams.id && enterParams.id !== id) {
        setId(enterParams.id);
      }
      if (enterParams.type !== undefined && enterParams.type !== dressType) {
        setDressType(enterParams.type);
      }
    }
  });

  useEffect(() => {
    if (id) {
      fetchDetail({ id });
    }
  }, [id]);

  const previewImages = useMemo(() => {
    const pictureList = detailData?.dressInfo?.pictureList;
    if (!pictureList) return [];
    
    // 确保是数组格式
    let images: string[] = [];
    if (Array.isArray(pictureList)) {
      images = pictureList;
    } else if (typeof pictureList === 'string') {
      // 如果是字符串，尝试解析为 JSON
      try {
        const parsed = parseJson(pictureList);
        images = Array.isArray(parsed) ? parsed : [parsed].filter(Boolean);
      } catch {
        // 如果解析失败，当作单个 URL 处理
        images = [pictureList].filter(Boolean);
      }
    }
    
    // 过滤掉空值和无效 URL
    return images.filter((url) => url && typeof url === 'string' && url.trim() !== '');
  }, [detailData?.dressInfo?.pictureList]);


  // 分享功能
  useShareAppMessage(() => {
    const shopId = Taro.getStorageSync(StorageKey.SHOP_ID);
    const currentDressType = detailData?.dressInfo?.dressType || dressType;
    let sharePath = `/pages/dress/detail/index?id=${id}`;
    if (currentDressType) {
      sharePath += `&type=${currentDressType}`;
    }
    if (shopId) {
      sharePath += `&shopId=${shopId}`;
    }
    return {
      title: detailData?.dressInfo?.name || '服装详情',
      path: sharePath,
      imageUrl: previewImages[0] || '',
    };
  });

  // 处理分享按钮点击
  const handleShare = () => {
    // 触发分享菜单
    Taro.showShareMenu({
      withShareTicket: true,
    });
  };

  // 处理预选按钮点击
  const handlePreselect = () => {
    // 检查是否已登录
    const token = Taro.getStorageSync(StorageKey.TOKEN);
    if (!token) {
      // 未登录，弹窗提示
      Toast.confirm({
        title: '提示',
        content: '请先登录后再进行预选',
        confirmText: '去登录',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            // 保存当前页面路径和参数，用于登录后返回
            const currentPath = router.path;
            const query = router.params;
            const paramsString = qs.stringify(query);
            const returnPath = `${currentPath}${paramsString ? `?${paramsString}` : ''}`;
            Taro.setStorageSync(StorageKey.APP_START_REDIRECT_PATH, returnPath);
            // 跳转到登录页面
            Taro.navigateTo({ url: '/pages/user/login/index' });
          }
        },
      });
      return;
    }

    // 已登录，保存服饰信息到store
    addDress(detailData?.dressInfo);
    Toast.success('已加入预选');
  };

  return (
    <BasicLayout
      title=''
      back
      fill
      className={styles.page}
      loading={loading}
      footer={{
        children: (
          <View className={styles.footer}>
            <Button
              className={`${styles.footerButton} ${styles.shareButton}`}
              onClick={handleShare}
              fill="outline"
              openType='share'
            >
              分享
            </Button>
            <Button
              className={`${styles.footerButton} ${styles.preselectButton} ${isPreselected ? styles.disabled : ''}`}
              onClick={handlePreselect}
              type="primary"
              disabled={isPreselected}
            >
              {isPreselected ? '已预选' : '预选'}
            </Button>
          </View>
        ),
      }}
    >
      <View className={`${styles.content}`}>
        <View className={styles.title}>{detailData?.dressInfo?.name}</View>
        {/* 产品信息 */}
        <ProductInfo data={detailData?.dressInfo} />

        <Divider />

        {/* 预览 */}
        {previewImages.length > 0 && (
          <Section title="预览" className={styles.section}>
            <View className={styles.previewGrid}>
              {previewImages.map((image, index) => (
                <View key={index} className={styles.previewItem}>
                  <Media
                    src={image}
                    mode="aspectFill"
                    preview
                    className={styles.previewMedia}
                    width="100%"
                    height="100%"
                  />
                </View>
              ))}
            </View>
          </Section>
        )}
        
      </View>
    </BasicLayout>
  );
}

export default Detail;
